package tx.bjdacp.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.sql.DataSource;

import org.apache.struts2.ServletActionContext;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import cn.org.rapid_framework.beanutils.BeanUtils;
import cn.org.rapid_framework.web.scope.Flash;

import com.opensymphony.xwork2.Preparable;
import com.opensymphony.xwork2.ModelDriven;

import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import javacommon.base.*;
import javacommon.util.*;

import cn.org.rapid_framework.util.*;
import cn.org.rapid_framework.web.util.*;
import cn.org.rapid_framework.page.*;
import cn.org.rapid_framework.page.impl.*;

import tx.bjdacp.model.*;
import tx.bjdacp.dao.*;
import tx.bjdacp.service.*;
import tx.bjdacp.util.WebUtils;
import tx.bjdacp.vo.SellUnitSupGspGatherVo;
import tx.bjdacp.vo.query.*;

public class DrugSellUnitAction extends BaseStruts2Action implements
		Preparable, ModelDriven {
	// 默认多列排序,example: username desc,createTime asc
	protected static final String DEFAULT_SORT_COLUMNS = null;

	// forward paths
	protected static final String QUERY_JSP = "/pages/DrugSellUnit/query.jsp";
	protected static final String LIST_JSP = "/pages/DrugSellUnit/list.jsp";
	protected static final String CREATE_JSP = "/pages/DrugSellUnit/create.jsp";
	protected static final String EDIT_JSP = "/pages/DrugSellUnit/edit.jsp";
	protected static final String SHOW_JSP = "/pages/DrugSellUnit/show.jsp";
	// redirect paths,startWith: !
	protected static final String LIST_ACTION = "!/pages/DrugSellUnit/list.do";

	private DrugSellUnitManager drugSellUnitManager;

	private DrugSellUnit drugSellUnit;
	java.lang.Integer id = null;
	private String[] items;
	private DrugSellUnitModifyLog drugSellUnitModifyLog;

	public void prepare() throws Exception {
		if (isNullOrEmptyString(id)) {
			drugSellUnit = new DrugSellUnit();
		} else {
			drugSellUnit = (DrugSellUnit) drugSellUnitManager.getById(id);
			if (getRequest().getParameter("isModify") != null) {// 企业信息变更（保留变更记录）
				drugSellUnitModifyLog = new DrugSellUnitModifyLog();
				try {
					PageRequestFactory.beanUtils.copyProperties(
							drugSellUnitModifyLog, drugSellUnit);
				} catch (IllegalAccessException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		}
	}

	/** 增加setXXXX()方法,spring就可以通过autowire自动设置对象属性,注意大小写 */
	public void setDrugSellUnitManager(DrugSellUnitManager manager) {
		this.drugSellUnitManager = manager;
	}

	public Object getModel() {
		return drugSellUnit;
	}

	public void setDrugSellUnitId(java.lang.Integer val) {
		this.id = val;
	}

	public void setItems(String[] items) {
		this.items = items;
	}

	/** 执行搜索 */
	public String list() {
		DrugSellUnitQuery query = newQuery(DrugSellUnitQuery.class,
				DEFAULT_SORT_COLUMNS);

		Page page = drugSellUnitManager.findPage(query);
		savePage(page, query);
		return LIST_JSP;
	}

	public String partTimeJobList() {
		DrugSellUnitQuery query = newQuery(DrugSellUnitQuery.class,
				DEFAULT_SORT_COLUMNS);

		Page page = drugSellUnitManager.findPagePartTimeJob(query);
		savePage(page, query);
		return LIST_JSP;
	}

	private GspInfoManager gspInfoManager;

	public void setGspInfoManager(GspInfoManager manager) {
		this.gspInfoManager = manager;
	}

	private SuperviseInfoManager superviseInfoManager;

	public void setSuperviseInfoManager(SuperviseInfoManager manager) {
		this.superviseInfoManager = manager;
	}

	/**
	 * 检查情况汇总分析
	 *
	 * @return
	 */
	public String listSupGspGather() {

		DrugSellUnitQuery query = newQuery(DrugSellUnitQuery.class,
				DEFAULT_SORT_COLUMNS);
		query.setPageSize(100);



		Page page = drugSellUnitManager.findPage(query);
		List result = page.getResult();
		List sellUnitSupGspGatherVos = new ArrayList();
		for (Iterator iterator = result.iterator(); iterator.hasNext();) {
			DrugSellUnit drugSellUnit = (DrugSellUnit) iterator.next();
			SellUnitSupGspGatherVo sv = new SellUnitSupGspGatherVo();
			sv.setDrugSellUnitId(drugSellUnit.getDrugSellUnitId());
			sv.setFileNumber(drugSellUnit.getFileNumber());
			sv.setUnitName(drugSellUnit.getUnitName());
			if (!isNullOrEmptyString(drugSellUnit.getZone())) {
				sv.setZoneName(drugSellUnit.getZone().getZoneName());
			}

			if (!isNullOrEmptyString(query.getYear())) {
				DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
				Date fromDate = new Date();
				Date toDate = new Date();
				try {
					fromDate = fmt.parse(query.getYear() + "-01-01");
					toDate = fmt.parse(query.getYear() + "-12-31");
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				// GSP认证
				GspInfoQuery gsp_query = newQuery(GspInfoQuery.class, null);
				gsp_query.setSortColumns(null);
				gsp_query.setPageSize(100);
				gsp_query.setGspGiveDateBegin(fromDate);
				gsp_query.setGspGiveDateEnd(toDate);
				gsp_query.setDrugSellUnitId(drugSellUnit.getDrugSellUnitId());
				Page gsp_page = gspInfoManager.findPage(gsp_query);
				List gsp_result = gsp_page.getResult();
				Set gsp_set = new HashSet();
				for (Iterator iterator2 = gsp_result.iterator(); iterator2
						.hasNext();) {
					GspInfo gi = (GspInfo) iterator2.next();
					gsp_set.add(gi);
				}
				sv.setGspInfos(gsp_set);

				// GSP跟踪检查
				SuperviseInfoQuery si_gsp_query = newQuery(
						SuperviseInfoQuery.class, null);
				si_gsp_query.setSortColumns(null);
				si_gsp_query.setPageSize(100);
				si_gsp_query.setSuperviseDateBegin(fromDate);
				si_gsp_query.setSuperviseDateEnd(toDate);
				si_gsp_query
						.setDrugSellUnitId(drugSellUnit.getDrugSellUnitId());
				si_gsp_query.setSuperviseType("跟踪检查");
				Page si_gsp_page = superviseInfoManager.findPage(si_gsp_query);
				List si_gsp_result = si_gsp_page.getResult();
				Set si_gsp_set = new HashSet();
				for (Iterator iterator2 = si_gsp_result.iterator(); iterator2
						.hasNext();) {
					SuperviseInfo si_gsp = (SuperviseInfo) iterator2.next();
					si_gsp_set.add(si_gsp);
				}
				sv.setSuperviseInfosAuditTrail(si_gsp_set);

				// 监督检查
				SuperviseInfoQuery si_query = newQuery(
						SuperviseInfoQuery.class, null);
				si_query.setSortColumns(null);
				si_query.setPageSize(100);
				si_query.setSuperviseDateBegin(fromDate);
				si_query.setSuperviseDateEnd(toDate);
				si_query.setDrugSellUnitId(drugSellUnit.getDrugSellUnitId());
				Page si_page = superviseInfoManager.findPage(si_query);
				List si_result = si_page.getResult();
				Set si_set = new HashSet();
				for (Iterator iterator2 = si_result.iterator(); iterator2
						.hasNext();) {
					SuperviseInfo si = (SuperviseInfo) iterator2.next();
					si_set.add(si);
				}
				sv.setSuperviseInfos(si_set);
			}
				sellUnitSupGspGatherVos.add(sv);

		}
		page.setResult(sellUnitSupGspGatherVos);

		savePage(page, query);

		return "/pages/DrugSellUnit/list-sup-gsp-gather.jsp";
	}

	public String listSupGspGatherExcel() {

		DrugSellUnitQuery query = newQuery(DrugSellUnitQuery.class,
				DEFAULT_SORT_COLUMNS);
		query.setPageSize(10000);



		Page page = drugSellUnitManager.findPage(query);
		List result = page.getResult();
		List sellUnitSupGspGatherVos = new ArrayList();
		for (Iterator iterator = result.iterator(); iterator.hasNext();) {
			DrugSellUnit drugSellUnit = (DrugSellUnit) iterator.next();
			SellUnitSupGspGatherVo sv = new SellUnitSupGspGatherVo();
			sv.setDrugSellUnitId(drugSellUnit.getDrugSellUnitId());
			sv.setFileNumber(drugSellUnit.getFileNumber());
			sv.setUnitName(drugSellUnit.getUnitName());
			if (!isNullOrEmptyString(drugSellUnit.getZone())) {
				sv.setZoneName(drugSellUnit.getZone().getZoneName());
			}

			if (!isNullOrEmptyString(query.getYear())) {
				DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
				Date fromDate = new Date();
				Date toDate = new Date();
				try {
					fromDate = fmt.parse(query.getYear() + "-01-01");
					toDate = fmt.parse(query.getYear() + "-12-31");
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				// GSP认证
				GspInfoQuery gsp_query = newQuery(GspInfoQuery.class, null);
				gsp_query.setSortColumns(null);
				gsp_query.setPageSize(100);
				gsp_query.setGspGiveDateBegin(fromDate);
				gsp_query.setGspGiveDateEnd(toDate);
				gsp_query.setDrugSellUnitId(drugSellUnit.getDrugSellUnitId());
				Page gsp_page = gspInfoManager.findPage(gsp_query);
				List gsp_result = gsp_page.getResult();
				Set gsp_set = new HashSet();
				for (Iterator iterator2 = gsp_result.iterator(); iterator2
						.hasNext();) {
					GspInfo gi = (GspInfo) iterator2.next();
					gsp_set.add(gi);
				}
				sv.setGspInfos(gsp_set);

				// GSP跟踪检查
				SuperviseInfoQuery si_gsp_query = newQuery(
						SuperviseInfoQuery.class, null);
				si_gsp_query.setSortColumns(null);
				si_gsp_query.setPageSize(100);
				si_gsp_query.setSuperviseDateBegin(fromDate);
				si_gsp_query.setSuperviseDateEnd(toDate);
				si_gsp_query
						.setDrugSellUnitId(drugSellUnit.getDrugSellUnitId());
				si_gsp_query.setSuperviseType("跟踪检查");
				Page si_gsp_page = superviseInfoManager.findPage(si_gsp_query);
				List si_gsp_result = si_gsp_page.getResult();
				Set si_gsp_set = new HashSet();
				for (Iterator iterator2 = si_gsp_result.iterator(); iterator2
						.hasNext();) {
					SuperviseInfo si_gsp = (SuperviseInfo) iterator2.next();
					si_gsp_set.add(si_gsp);
				}
				sv.setSuperviseInfosAuditTrail(si_gsp_set);

				// 监督检查
				SuperviseInfoQuery si_query = newQuery(
						SuperviseInfoQuery.class, null);
				si_query.setSortColumns(null);
				si_query.setPageSize(100);
				si_query.setSuperviseDateBegin(fromDate);
				si_query.setSuperviseDateEnd(toDate);
				si_query.setDrugSellUnitId(drugSellUnit.getDrugSellUnitId());
				Page si_page = superviseInfoManager.findPage(si_query);
				List si_result = si_page.getResult();
				Set si_set = new HashSet();
				for (Iterator iterator2 = si_result.iterator(); iterator2
						.hasNext();) {
					SuperviseInfo si = (SuperviseInfo) iterator2.next();
					si_set.add(si);
				}
				sv.setSuperviseInfos(si_set);
			}
				sellUnitSupGspGatherVos.add(sv);

		}
		page.setResult(sellUnitSupGspGatherVos);

		savePage(page, query);

		return "/pages/DrugSellUnit/list-sup-gsp-gather-excel.jsp";
	}

	public String listExcel() {
		DrugSellUnitQuery query = newQuery(DrugSellUnitQuery.class,
				DEFAULT_SORT_COLUMNS);
		query.setPageSize(10000);
		Page page = drugSellUnitManager.findPage(query);
		savePage(page, query);
		return "/pages/DrugSellUnit/list-excel.jsp";
	}

	/** 查看对象 */
	public String show() {
		return SHOW_JSP;
	}

	/** 进入新增页面 */
	public String create() {
		return CREATE_JSP;
	}

	/** 保存新增对象 */
	public String save() {
		drugSellUnitManager.save(drugSellUnit);
		Flash.current().success(CREATED_SUCCESS); // 存放在Flash中的数据,在下一次http请求中仍然可以读取数据,error()用于显示错误消息
		return LIST_ACTION;
	}

	/** 进入更新页面 */
	public String edit() {
		return EDIT_JSP;
	}

	/** 保存更新对象 */
	public String update() {
		drugSellUnitManager.update(this.drugSellUnit);
		Flash.current().success(UPDATE_SUCCESS);
		return LIST_ACTION;
	}

	/** 删除对象 */
	public String delete() {
		for (int i = 0; i < items.length; i++) {
			Hashtable params = HttpUtils.parseQueryString(items[i]);
			java.lang.Integer id = new java.lang.Integer(
					(String) params.get("drugSellUnitId"));
			drugSellUnitManager.removeById(id);
		}
		Flash.current().success(DELETE_SUCCESS);
		return LIST_ACTION;
	}

	private DrugSellUnitModifyLogManager drugSellUnitModifyLogManager;

	public void setDrugSellUnitModifyLogManager(
			DrugSellUnitModifyLogManager manager) {
		this.drugSellUnitModifyLogManager = manager;
	}

	public String modify() {

		drugSellUnitModifyLog.setModifyDate(new Date());
		drugSellUnitModifyLog.setUserInfoId(WebUtils.getUserInSession()
				.getUserInfoId());
		drugSellUnitModifyLogManager.save(drugSellUnitModifyLog);
		Flash.current().success(UPDATE_SUCCESS);
		return SHOW_JSP;
	}

	public String modifyPhoneData() {
		ApplicationContext applicationContext = WebApplicationContextUtils
				.getWebApplicationContext(ServletActionContext
						.getServletContext());
		DataSource ds = (DataSource) applicationContext.getBean("dataSource");
		try {
			Connection conn = ds.getConnection();
			PreparedStatement ps = conn
					.prepareStatement("SELECT 企业名称, 联系人, LTRIM(STR(联系方式手机, 20, 0)) AS 联系方式手机, LTRIM(STR(联系方式座机, 20, 0)) AS 联系方式座机 FROM 企业联系方式7_20");
			ResultSet rs = ps.executeQuery();
			int i = 0;
			while (rs.next()) {
				String qymc = rs.getString("企业名称").trim();
				qymc = qymc.replaceAll("[^\u4e00-\u9fa5]", "");
				String mobilePhone = rs.getString("联系方式手机");
				String phone = rs.getString("联系方式座机");
				String person = rs.getString("联系人");

				DrugSellUnitDao dao = (DrugSellUnitDao) drugSellUnitManager
						.getEntityDao();
				List<DrugSellUnit> dsus = dao.findAllBy("unitName", qymc);

				if (dsus.size() == 0) {
					log.info("未找到" + " " + qymc);
					i++;
				} else {
					for (DrugSellUnit drugSellUnit : dsus) {
						if (mobilePhone != null) {
							drugSellUnit.setMobelPhone(drugSellUnit
									.getMobelPhone()
									+ mobilePhone
									+ "（"
									+ person + "） ");
						}
						if (phone != null) {
							drugSellUnit.setPhone(drugSellUnit.getPhone()
									+ phone + "（" + person + "） ");
						}
					}
				}

			}
			log.info(i);
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Flash.current().success(UPDATE_SUCCESS);
		return null;
	}

}
